import AV from 'leancloud-storage';
import WechatyManager from './room-manager';
import Logger from './logger';
import { intervalTimes, excuteIntervalRightNow } from './utils';

AV.init({
  appId: 'l1buxITuSPQL5MatNdwhtcm2-gzGzoHsz',
  appKey: 'LVpkrT2ioDeTL92xHsafKnRb',
});

/**
 *
 * @class WxRoom
 */
class WxRoom {

  constructor(){
    // excuteIntervalRightNow(() => {
    //   const qrcodeQuery = new AV.Query('qrcode_info');
    //   qrcodeQuery.equalTo('status', 'reviewing');
    //   qrcodeQuery
    //   .find()
    //   .then(result => {
    //     this.validGroup(result.map(value => ({
    //       id: value.get('objectId'),
    //       topic: value.get('name'),
    //       owner: value.get('owner'),
    //     })));
    //   });
    // }, 1000*60*15);
    this.wechatyManager = new WechatyManager();
  }

  hasRoom = async (groupInfo) => {
    const rooms = await this.wechatyManager.findRooms(groupInfo.topic);
    return rooms.some(room => {
      return groupInfo.topic === room.topic();
    })
  }

  validGroup(groupInfos){
    Logger.info('groupInfos %s',JSON.stringify(groupInfos));
    groupInfos.map(groupInfo => {
      intervalTimes(10, this.hasRoom, 1000*30, groupInfo)
      .then(res => {
        AV.Query.doCloudQuery(`update qrcode_info set status="success" where objectId="${res.id}"`);
      })
      .catch(res => {
        AV.Query.doCloudQuery(`update qrcode_info set status="failed" where objectId="${res.id}"`);
        this.wechatyManager.saySelf(`审核失败：${JSON.stringify(res)}`);
      })
    })
  }
}

(async function(){
  const wxRoom = new WxRoom();
  await wxRoom.wechatyManager.startBot();
})();
